/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null) return head;
        ListNode head1 = head;
        int length = getLength(head1);
        k = k % length;
        // 慢指针初始指向头节点
    ListNode slow = head;
    // 快指针初始指向头节点
    ListNode fast = head;

    // 快指针先向前移动k步
    for(int i = 0; i < k; i++) {
        fast= fast.next;
    }

    // 快慢指针同时向前移动，直到快指针指向的节点的
    // 下一个节点为null
    while (fast.next != null) {
        fast = fast.next;
        slow = slow.next;
    }

    // 快指针此时在链表末尾
    // 然后其指向的节点的后继指针指向头节点
    // 这时链表首尾相连成环
    fast.next = head;
    // 新的头节点是慢指针所指节点的下一个节点
    head = slow.next;
    // 慢指针所指节点的的后继指针指向null
    // 断开环
    slow.next = null;
    return head;
    }
    public int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            ++length;
            head = head.next;
        }
        return length;
    }
}